/**
 * @file       IEventListener.cpp
 * @brief      TODO
 * @author     Huabo Zheng
 * @date       Jan 13, 2012
 * @Copyright  2012, www.netgear.com Inc. All rights reserved.
 */

#include "IEventListener.h"
#include "EventHandler.h"
#include "typedefine.h"
#include "errorcode.h"
#include "IEvent.h"
#include "Frame.h"

namespace NS_LCD_AFW
{

IEventListener::IEventListener() :
		m_bAutoReleaae(true), m_iEventId(INVALID_PARAM), m_iParam(
				INVALID_PARAM), m_pCallBack(NULL), m_pEventHandler(NULL), m_pOwner(
				NULL)
{

}

IEventListener::IEventListener(CEventHandler *pEventHandler,
		bool bAutoRelease/* = true*/) :
		m_bAutoReleaae(bAutoRelease), m_iEventId(INVALID_PARAM), m_iParam(
				INVALID_PARAM), m_pCallBack(NULL), m_pEventHandler(
				pEventHandler), m_pOwner(pEventHandler)
{
}

IEventListener::IEventListener(CEventHandler *pEventHandler, int eventId,
		AFW_EventCallBack callBack, int param, bool bAutoRelease /* = true*/) :
		m_bAutoReleaae(bAutoRelease), m_iEventId(eventId), m_iParam(param), m_pCallBack(
				callBack), m_pEventHandler(pEventHandler)
{
}

IEventListener::~IEventListener()
{
	m_pEventHandler = NULL;
	m_pOwner = NULL;
}

CEventHandler *IEventListener::getEventHandler() const
{
	return m_pEventHandler;
}

CEventHandler * IEventListener::setEventHandler(CEventHandler *pEventHandler)
{
	CEventHandler *pOldHandler = m_pEventHandler;
	m_pEventHandler = pEventHandler;
	return pOldHandler;
}

bool IEventListener::isAutoReleaae() const
{
	return m_bAutoReleaae;
}

void IEventListener::setAutoReleaae(bool bAutoReleaae)
{
	m_bAutoReleaae = bAutoReleaae;
}

int IEventListener::actionPerformed(IEvent *pEvent)
{

	if (NULL != m_pEventHandler)
	{
		//Get the framework a chance to intercept or hook the messages
		if (ERR_SUCCESS == m_pEventHandler->handlerEvent(pEvent))
		{
			return ERR_SUCCESS;
		}
		else if (NULL != pEvent && pEvent->getEventId() == this->m_iEventId
				&& NULL != m_pOwner)
		{
			AFW_EventCallBack pCallBack = m_pEventHandler->getCallBack(
					pEvent->getEventId() ^ m_pOwner->getObjId());
			if (NULL != pCallBack)
			{
				(m_pEventHandler->*pCallBack)(pEvent->getEventId(),
						this->m_iParam); //the framework does't care aboult the result code that user return
				return ERR_SUCCESS;
			}
		}
	}
	if (NULL != pEvent)
	{
		return pEvent->doProcess(dynamic_cast<CFrame *>(this->m_pOwner));
	}

	return ERR_INVALID_EVENTHANDLER;
}

void IEventListener::destory()
{
	if (m_bAutoReleaae)
	{
		delete this;
	}
}

void IEventListener::setOwner(CEventHandler *pOwner)
{
	this->m_pOwner = pOwner;

	if (NULL != this->m_pEventHandler && NULL != m_pOwner)
	{
		m_pEventHandler->registerCallBack(
				this->m_iEventId ^ m_pOwner->getObjId(), this->m_pCallBack);
	}
}
}
/* namespace NS_LCD_AFW */
